package link.anyauto.j2m.multithread;

import android.os.Handler;

import java.util.concurrent.Callable;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

import link.anyauto.j2m.App;
import link.anyauto.j2m.MultiThreadAct;

/**
 * Created by LYQ on 2016/5/11.
 */
public class MultiThreadDemo {
    public MultiThreadDemo(Handler uiHandler) {
        this.uiHandler = uiHandler;
    }

    public void start() {
        new Thread(){
            @Override
            public void run() {
                try {
                    futureWithRunnable();
                    futureWithCallable();
                    futureWithFutureTask();
                } catch (Exception e){
                    e.printStackTrace();
                }
                uiHandler.obtainMessage(MultiThreadAct.MSG_LOG, "任务执行完毕。").sendToTarget();
            }
        }.start();
    }

    void futureWithRunnable() throws Exception {
        Future<?> res = exec.submit(new Runnable() {
            @Override
            public void run() {
                timeConsumingJob("Runnable");
            }
        });
        uiHandler.obtainMessage(MultiThreadAct.MSG_LOG, "Runnable任务执行结果：" + res.get()).sendToTarget();
    }

    void futureWithCallable() throws Exception{
        Future<?> res = exec.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return timeConsumingJob("Callable");
            }
        });
        uiHandler.obtainMessage(MultiThreadAct.MSG_LOG, "Callable任务执行结果：" + res.get()).sendToTarget();
    }

    void futureWithFutureTask() throws Exception{
        FutureTask<Long> task = new FutureTask<Long>(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return timeConsumingJob("FutureTask");
            }
        });
        exec.submit(task);
        uiHandler.obtainMessage(MultiThreadAct.MSG_LOG, "FutureTask任务执行结果：" + task.get()).sendToTarget();
        // shutdown after the last job finished.
        exec.shutdown();
    }

    long timeConsumingJob(String name) {
        long sleepTime = 500 + (long)(Math.random() * 500);
        App.sleep(sleepTime);
        uiHandler.obtainMessage(MultiThreadAct.MSG_LOG, name + "任务执行了：" + sleepTime + "毫秒。").sendToTarget();
        return sleepTime;
    }

    Handler uiHandler;
    ExecutorService exec = Executors.newSingleThreadExecutor();
}
